package com.bw.broker.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bw.broker.service.TbUserService;
import com.bw.broker.mapper.TbUserMapper;
import com.bw.po.TbUser;
import com.bw.result.ResponseState;
import com.bw.result.ResultVo;
import com.bw.util.SnowflakeIdWorker;
import com.bw.vo.IdVo;
import com.bw.vo.TbUserSearchVo;
import com.bw.vo.TbUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author lenovo
* @description 针对表【tb_user(用户表)】的数据库操作Service实现
* @createDate 2023-11-16 10:45:47
*/
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser>
    implements TbUserService{

    private SnowflakeIdWorker idWorker = new SnowflakeIdWorker(0,0);

    @Autowired
    private TbUserMapper tbUserMapper;

    @Override
    public ResultVo listBySearchVo(TbUserSearchVo tbUserSearchVo) {
        Page<TbUser> page = new Page<>(tbUserSearchVo.getPageNum(), tbUserSearchVo.getPageSize());
        Page<TbUserVo> pageList = tbUserMapper.listBySearchVo(page, tbUserSearchVo);
        return ResultVo.SUCCESS(pageList);
    }

    @Override
    public ResultVo delete(IdVo idVo) {
        int flag = tbUserMapper.deleteById(idVo.getId());
        return flag>0?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.DELETE_ERROR);
    }

    @Override
    public ResultVo add(TbUserVo tbUserVo) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(TbUser::getName,tbUserVo.getName());
        TbUser user = this.getOne(wrapper);
        if (user!=null){
            return ResultVo.FAILED(ResponseState.USER_EXIST);
        }

        tbUserVo.setId(String.valueOf(idWorker.nextId()));

        TbUser tbUser = new TbUser();
        BeanUtils.copyProperties(tbUserVo, tbUser);

        int flag = tbUserMapper.insert(tbUser);
        return flag>0?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.INSERT_ERROR);
    }

    @Override
    public ResultVo updateByVo(TbUserVo tbUserVo) {
        TbUser tbUser = new TbUser();
        BeanUtils.copyProperties(tbUserVo, tbUser);

        int flag = tbUserMapper.updateById(tbUser);
        return flag>0?ResultVo.SUCCESS():ResultVo.FAILED(ResponseState.UPDATE_ERROR);
    }
}




